#coding=utf-8
#从百度移动端日历关键字搜索结果获取
from browser.ff import driver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.wait import WebDriverWait
import os


import datetime

import time

import sys



if getattr(sys, 'frozen', False):
    root_path = os.path.dirname(sys.executable)
elif __file__:
    root_path = os.path.dirname(__file__)


#urlip = "172.25.62.23"#西安
#urlip = "219.232.50.39"#北京
#urlip = "172.18.71.35:8080"#北京新
urlip = "59.109.37.211:8080"#北京新




if len(sys.argv)==3:
    username = sys.argv[1]
    password = sys.argv[2]
else:
    username = input("请输入用户名：")
    password = input("请输入密码：")

    #sys.exit()

print("欢迎您 %s"%username)

#month = input("请输入填写月份（1至12数字）：")
#driver.get("https://www.baidu.com/from=844b/s?word=%E6%97%A5%E5%8E%86&ts=4492725&t_kt=798347&ie=utf-8&fm_kl=021394be2f&rsv_iqid=2649084771&rsv_t=ba88wimKL04D7dsKRroAYRvFbK20rPOFhpbs0ipI66OkJSQXvQQJhDNWxw&sa=ib&ms=1&rsv_pq=2649084771&rsv_sug4=3490&inputT=121&ss=100&tj=1")
driver.get("https://m.so.com/s?q=%E6%97%A5%E5%8E%862023%E5%B9%B42%E6%9C%88&src=result_input&srcg=home_next&psid=52029848c5b7076ae8951aeb8fc370f3&sug_pos=&sug=&_ms=0&dm_ms-ui=0&ms_ui=1")
driver.get("https://m.so.com/s?q=%E6%97%A5%E5%8E%862023%E5%B9%B44%E6%9C%88&src=result_input&srcg=home_next&psid=52029848c5b7076ae8951aeb8fc370f3&sug_pos=&sug=&_ms=0&dm_ms-ui=0&ms_ui=1")
time.sleep(1)

#获取日历信息
#month = -1 #为0 则使用当前月  -1 上一个月




# if month == -1:
#     print("查询上月")
#     driver.find_element_by_xpath("/html/body/div[1]/section/div/div[1]/div[1]/calendar/section/div[2]/a[1]").click()
#     #driver.find_element_by_css_selector(".mh-prev").click()
# else:
#     month = 0

#当月所有可选日期
#百度移动端（2019年7月2日15:53:01 已经作废不可用）
# work_data = [i.get_attribute('data-date') for i in driver.find_elements_by_css_selector('#results .wa-calendars-td-normal:not(.wa-calendars-td-holiday):not(.wa-calendars-td-weekend)')]
# print(work_data)
# work_data = [datetime.datetime.strptime(i, "%Y-%m-%d") for i in work_data]
#360移动端 获取日历

work_data1 = [i.get_attribute('date') for i in driver.find_elements_by_css_selector('#mohe-m-calendar .mh-query li:not(.mh-weekend):not(.mh-cross-month):not(.mh-rest)')]
print(work_data1)
work_data2 = [i.get_attribute('data') for i in driver.find_elements_by_css_selector('#mohe-m-calendar .mh-query .mh-weekend.mh-work')]
print(work_data2)

work_data = [datetime.datetime.strptime(i, "%Y/%m/%d") for i in work_data1]
print(work_data)
print(u"【上月工作日】:")

for i in work_data:
    print(i)


time.sleep(10)
driver.get("http://%s/rdms/login.jsp"%urlip)
driver.find_element_by_css_selector("input[name='username']").send_keys(username)
driver.find_element_by_css_selector("input[name='password']").send_keys(password)
driver.find_element_by_css_selector(".loginButton").click()

#如果网址跳转到了 http://219.232.50.39/rdms/explorer.jsp 则视为登陆成功
try:
    WebDriverWait(driver, 6, 1).until(EC.url_matches("http://%s/rdms/explorer.jsp"%urlip))
    print("登陆成功")
except:
    print("密码错误或者服务器没响应,请重试")
    sys.exit()

finally:
    pass


print("获取已经写的日志信息")

#driver.get("http://%s/rdms/personal/actions/WorkJourManage+.do?method=resetMyQuery&executeQueryClass=com.chinaspis.personal.query.PersonalWorkJourQuery&forwardPage=/personal/views/ListPersonalWorkJourView.jsp&functionID=PersonalWorkJour&pagination=true"%urlip)

driver.get("http://%s/rdms/project/actions/WorkJourManage.do?method=showBatchAdd"%urlip)


time.sleep(1)
#得到已经写好的列表
yc_data = [i.text for i in driver.find_elements_by_css_selector("#testTable .tablecells>a[title='详细信息']")]
yc_data = [datetime.datetime.strptime(i, "%Y-%m-%d") for i in yc_data]



qs = 0
#得到缺少的日期
for i in range(len(work_data)):
    if work_data[i] in yc_data:
        print(work_data[i],"写了")
        work_data[i] = 0
    else:
        print(work_data[i],"还没写")



if len(work_data) == 0:
    print("没有缺失的日志信息，程序10秒后结束")
    time.sleep(10)
    sys.exit()



work_data2 = work_data.copy()

#删除已经写了的日期
for i2 in range(len(work_data2)):
    if work_data2[i2]==0:
        work_data.remove(0)








if len(work_data) == 0:
    print("都写了")
else:
    print("还有",len(work_data),"天没写")
    print("开始填写表单吧")
    driver.get("http://%s/rdms/project/actions/WorkJourManage.do?method=showBatchAdd"%urlip)
    time.sleep(1)
    if len(work_data)>10:
        xhcs = len(work_data)-10
        js = "for (var i=0;i<%s;i++){$('.futuretable>tbody').append($('.futuretable>tbody>tr:last').clone())}"%xhcs
        driver.execute_script(js)
    elif len(work_data)<10:
        xhcs = 10-len(work_data)
        js = "for (var i=0;i<%s;i++){$('.futuretable>tbody').append($('.futuretable>tbody>tr:last').remove())}"%xhcs
        driver.execute_script(js)
    else:
        pass
    selecthtml = driver.find_element_by_xpath('/html/body/div/form/table[2]/tbody/tr[1]/td[2]').get_attribute('innerHTML')

    selecthtml = selecthtml.replace('\n', '')
    js  = "$('body').append('<div id=allselectzl style=\"position:absolute\">请在30秒内选择好 %s</div>')"%selecthtml
    driver.execute_script(js)
    js = "$('#allselectzl select').change(function(){var c= $(this).children('option:selected').val();$('.futuretable > tbody:nth-child(2) > tr > td:nth-child(2) select').val(c);})"
    driver.execute_script(js)
    #读取本地txt
    print("请在页面左上角选择项目 （30秒内）,30秒后将开始自动填写日志，自动填写时请不要操作")




    #填写日期
    time.sleep(1)

    for i,datainput in enumerate(driver.find_elements_by_css_selector(".futuretable input[name='workjourDate']")):
        if len(work_data)>i:
            js = "$(\".futuretable>tbody>tr:eq(%s) input[name=\'workjourDate\']\").val(\'%s\')"%(i,work_data[i].strftime('%Y-%m-%d'))
            driver.execute_script(js)
            #print(work_data[i].strftime('%Y-%m-%d'))
            #datainput.send_keys(11)
        else:
            js = "$(\".futuretable>tbody>tr:last\").remove()"
            driver.execute_script(js)

    js = "$(\".futuretable>tbody select[name=\'type\']\").val(\'编码(含代码走查/单元测试)\');$(\".futuretable>tbody input[name=\'workload\']\").val(\'8\')"

    driver.execute_script(js)


    xuanrenobjs = driver.find_elements_by_xpath(' / html / body / div[1] / form / table[2] / tbody / tr / td[7] / select')

    textareabjs = driver.find_elements_by_xpath(' / html / body / div / form / table[2] / tbody / tr / td[6] / textarea')

    time.sleep(30)

    infile = root_path+'/rdms.txt'
    f = open(infile, 'r')
    sourceInLine = f.readlines()

    # for line in sourceInLine:
    #     print(line)

    i6 = 0
    for s in xuanrenobjs:
        textareabjs[i6].send_keys(sourceInLine[i6])
        i6 = i6 +1
        s.find_element_by_xpath("option[@value='3']").click()

    print("自动化操作完成，请点击提交")






